// src/pages/home/widgets/userChannel/index.tsx
import { useRequestUserChannelsQuery } from "@service/channel";
import styles from "@pages/home/widgets/channel/styles/styles.module.less";
import classNames from "classnames";
import useChannelScroll from "@pages/home/widgets/common/scroll";
import { useNavigate, useParams } from "react-router-dom";
import { useRef,useEffect } from "react";
export default function UserChannel() {
  const { data } = useRequestUserChannelsQuery(undefined);
  // 实现频道列表的滚动效果
  const { scrollHandler, scrollContainerRef } = useChannelScroll();
   // 获取路由参数
   const { cid } = useParams();
   // 获取用于实现页面跳转的方法
   const navigate = useNavigate();
   // 用于存储所有频道列表的 DOM 对象
  const userChannelsDOM = useRef<Record<number, HTMLDivElement>>({});

  // 检测 cid 是否变化
  useEffect(() => {
    // 如果 cid 变化
    if (scrollContainerRef.current != null && typeof cid !== "undefined") {
      // 设置滚动位置
      scrollHandler(userChannelsDOM.current[Number(cid)]);
    }
  }, [cid, scrollHandler, scrollContainerRef]);
  // 判断频道列表是否获取成功, 如果没有成功暂时什么都不渲染
  if (typeof data === "undefined") return null;
  // 频道列表获取成功, 渲染视图
  return (
    <div className={styles.list} ref={scrollContainerRef}>
      {data.data.channels.map((channel) => (
        <div
          key={channel.id}
          className={classNames(styles.item, { [styles.active]: channel.id === Number(cid), })}
          onClick={(event) => {scrollHandler(event.currentTarget);navigate(`/${channel.id}`)}}
          ref={(element) => {userChannelsDOM.current[channel.id] = element!;}}
        >
          {channel.name}
        </div>
      ))}
    </div>
  );
}